<template>
  <div class="tag-container">
    <div>
      <template v-for="tag in tags">
        <a-tag  :key="tag" :closable="true"
                :class="[!showUpdateBtn ? 'input-disable-tag':'']"
                @close="() => handleClose(tag)">
          {{ tag }}
        </a-tag>
      </template>
    </div>
    <a-input v-if="inputVisible" ref="input" type="text" size="small"
             :style="{ width: '78px',padding: '12px 0' }" :value="inputValue"
             @change="handleInputChange"
             @blur="handleInputConfirm"
             @keyup.enter.pervent="handleInputConfirm"
             @keydown="handleInputDown"
    />
    <a-tag v-else @click="showInput" :class="[!showUpdateBtn ? 'input-disable-tag-label':'add-tag-label']">
      添加标签
    </a-tag>
  </div>
</template>

<script>
  export default {
    name: 'TagContainer',
    props: {
      tags: Array,
      showUpdateBtn: Boolean
    },
    data () {
      return {
        inputVisible: false,
        inputValue: '',
        newTags: []
      };
    },
    watch: {
      tags: function (newVal) {
        console.log(newVal);
        if (newVal.length > 0) {
          for (let i  = 0; i < newVal.length; i++) {
            if (newVal[i] === '') {
              newVal.splice(i, 1);
            }
          }
          this.getLocalTags(newVal);
        }
      },
    },
    methods: {
      // 获取缓存的标签数;
      getLocalTags (tags) {
        this.newTags = tags;
      },
      handleClose (removedTag) {
        const tags = this.newTags.filter(tag => tag !== removedTag);
        //console.log(tags);
        this.newTags = tags;
        this.$emit('tagChange', this.newTags);
      },
      showInput () {
        this.inputVisible = true;
        this.$nextTick(function() {
          this.$refs.input.focus();
        });
      },
      handleInputChange (e) {
        this.inputValue = e.target.value;
      },
      handleInputDown (e) {
        if (e.keyCode === 13) {
          e.preventDefault();
          e.stopPropagation();
        }
      },
      handleInputConfirm () {
        const inputValue = this.inputValue;
        let ConfirmTags = this.newTags;
        if (inputValue && this.newTags.indexOf(inputValue) === -1) {
          ConfirmTags = [...this.newTags, inputValue];
        }
        //console.log(ConfirmTags);
        this.$emit('tagChange', ConfirmTags);
        Object.assign(this, {
          ConfirmTags,
          inputVisible: false,
          inputValue: '',
        });
      },
    }
  }
</script>

<style scoped="scoped">
  @import "./style.css";
</style>
